'use strict';
const appid = '你的AppID';
const secret = '你的AppSecret';
const db = uniCloud.database();
const userCollection = db.collection('user');
exports.main = async (event, context) => {
	const {
		code,
		avatarUrl,
		gender,
		nickName
	} = event;
	const url =
		`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
	const res = await uniCloud.httpclient.request(url, {
		method: 'GET',
		dataType: 'json'
	});
	const {
		openid
	} = res.data;
	// 检查用户是否已存在
	const countRes = await userCollection.where({
		openid
	}).count();
	if (countRes.total === 0) {
		await userCollection.add({
			openid,
			avatarUrl,
			gender,
			nickName
		});
	}
	return {
		openid,
		avatarUrl,
		gender,
		nickName
	};
};